/**
 * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package org.ossr.portlets.pm.service.persistence;

import com.liferay.portal.NoSuchModelException;
import com.liferay.portal.kernel.annotation.BeanReference;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.BatchSessionUtil;
import com.liferay.portal.service.persistence.ResourcePersistence;
import com.liferay.portal.service.persistence.UserPersistence;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import org.ossr.portlets.pm.NoSuchPrivateMessageException;
import org.ossr.portlets.pm.model.PrivateMessage;
import org.ossr.portlets.pm.model.impl.PrivateMessageImpl;
import org.ossr.portlets.pm.model.impl.PrivateMessageModelImpl;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * The persistence implementation for the private message service.
 *
 * <p>
 * Never modify or reference this class directly. Always use {@link PrivateMessageUtil} to access the private message persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
 * </p>
 *
 * <p>
 * Caching information and settings can be found in <code>portal.properties</code>
 * </p>
 *
 * @author Edgar Zavala
 * @see PrivateMessagePersistence
 * @see PrivateMessageUtil
 * @generated
 */
public class PrivateMessagePersistenceImpl extends BasePersistenceImpl<PrivateMessage>
	implements PrivateMessagePersistence {
	public static final String FINDER_CLASS_NAME_ENTITY = PrivateMessageImpl.class.getName();
	public static final String FINDER_CLASS_NAME_LIST = FINDER_CLASS_NAME_ENTITY +
		".List";
	public static final FinderPath FINDER_PATH_FIND_ALL = new FinderPath(PrivateMessageModelImpl.ENTITY_CACHE_ENABLED,
			PrivateMessageModelImpl.FINDER_CACHE_ENABLED,
			FINDER_CLASS_NAME_LIST, "findAll", new String[0]);
	public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(PrivateMessageModelImpl.ENTITY_CACHE_ENABLED,
			PrivateMessageModelImpl.FINDER_CACHE_ENABLED,
			FINDER_CLASS_NAME_LIST, "countAll", new String[0]);

	/**
	 * Caches the private message in the entity cache if it is enabled.
	 *
	 * @param privateMessage the private message to cache
	 */
	public void cacheResult(PrivateMessage privateMessage) {
		EntityCacheUtil.putResult(PrivateMessageModelImpl.ENTITY_CACHE_ENABLED,
			PrivateMessageImpl.class, privateMessage.getPrimaryKey(),
			privateMessage);
	}

	/**
	 * Caches the private messages in the entity cache if it is enabled.
	 *
	 * @param privateMessages the private messages to cache
	 */
	public void cacheResult(List<PrivateMessage> privateMessages) {
		for (PrivateMessage privateMessage : privateMessages) {
			if (EntityCacheUtil.getResult(
						PrivateMessageModelImpl.ENTITY_CACHE_ENABLED,
						PrivateMessageImpl.class,
						privateMessage.getPrimaryKey(), this) == null) {
				cacheResult(privateMessage);
			}
		}
	}

	/**
	 * Clears the cache for all private messages.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	public void clearCache() {
		CacheRegistryUtil.clear(PrivateMessageImpl.class.getName());
		EntityCacheUtil.clearCache(PrivateMessageImpl.class.getName());
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
	}

	/**
	 * Clears the cache for the private message.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	public void clearCache(PrivateMessage privateMessage) {
		EntityCacheUtil.removeResult(PrivateMessageModelImpl.ENTITY_CACHE_ENABLED,
			PrivateMessageImpl.class, privateMessage.getPrimaryKey());
	}

	/**
	 * Creates a new private message with the primary key. Does not add the private message to the database.
	 *
	 * @param messageId the primary key for the new private message
	 * @return the new private message
	 */
	public PrivateMessage create(long messageId) {
		PrivateMessage privateMessage = new PrivateMessageImpl();

		privateMessage.setNew(true);
		privateMessage.setPrimaryKey(messageId);

		return privateMessage;
	}

	/**
	 * Removes the private message with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param primaryKey the primary key of the private message to remove
	 * @return the private message that was removed
	 * @throws com.liferay.portal.NoSuchModelException if a private message with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public PrivateMessage remove(Serializable primaryKey)
		throws NoSuchModelException, SystemException {
		return remove(((Long)primaryKey).longValue());
	}

	/**
	 * Removes the private message with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param messageId the primary key of the private message to remove
	 * @return the private message that was removed
	 * @throws org.ossr.portlets.pm.NoSuchPrivateMessageException if a private message with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public PrivateMessage remove(long messageId)
		throws NoSuchPrivateMessageException, SystemException {
		Session session = null;

		try {
			session = openSession();

			PrivateMessage privateMessage = (PrivateMessage)session.get(PrivateMessageImpl.class,
					new Long(messageId));

			if (privateMessage == null) {
				if (_log.isWarnEnabled()) {
					_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + messageId);
				}

				throw new NoSuchPrivateMessageException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
					messageId);
			}

			return remove(privateMessage);
		}
		catch (NoSuchPrivateMessageException nsee) {
			throw nsee;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected PrivateMessage removeImpl(PrivateMessage privateMessage)
		throws SystemException {
		privateMessage = toUnwrappedModel(privateMessage);

		Session session = null;

		try {
			session = openSession();

			BatchSessionUtil.delete(session, privateMessage);
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

		EntityCacheUtil.removeResult(PrivateMessageModelImpl.ENTITY_CACHE_ENABLED,
			PrivateMessageImpl.class, privateMessage.getPrimaryKey());

		return privateMessage;
	}

	public PrivateMessage updateImpl(
		org.ossr.portlets.pm.model.PrivateMessage privateMessage, boolean merge)
		throws SystemException {
		privateMessage = toUnwrappedModel(privateMessage);

		Session session = null;

		try {
			session = openSession();

			BatchSessionUtil.update(session, privateMessage, merge);

			privateMessage.setNew(false);
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

		EntityCacheUtil.putResult(PrivateMessageModelImpl.ENTITY_CACHE_ENABLED,
			PrivateMessageImpl.class, privateMessage.getPrimaryKey(),
			privateMessage);

		return privateMessage;
	}

	protected PrivateMessage toUnwrappedModel(PrivateMessage privateMessage) {
		if (privateMessage instanceof PrivateMessageImpl) {
			return privateMessage;
		}

		PrivateMessageImpl privateMessageImpl = new PrivateMessageImpl();

		privateMessageImpl.setNew(privateMessage.isNew());
		privateMessageImpl.setPrimaryKey(privateMessage.getPrimaryKey());

		privateMessageImpl.setMessageId(privateMessage.getMessageId());
		privateMessageImpl.setOwnerId(privateMessage.getOwnerId());
		privateMessageImpl.setRecepients(privateMessage.getRecepients());
		privateMessageImpl.setCreationDate(privateMessage.getCreationDate());
		privateMessageImpl.setIsReply(privateMessage.isIsReply());
		privateMessageImpl.setReplyDate(privateMessage.getReplyDate());
		privateMessageImpl.setDeleted(privateMessage.isDeleted());
		privateMessageImpl.setReaded(privateMessage.isReaded());
		privateMessageImpl.setSubject(privateMessage.getSubject());
		privateMessageImpl.setBody(privateMessage.getBody());

		return privateMessageImpl;
	}

	/**
	 * Finds the private message with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found.
	 *
	 * @param primaryKey the primary key of the private message to find
	 * @return the private message
	 * @throws com.liferay.portal.NoSuchModelException if a private message with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public PrivateMessage findByPrimaryKey(Serializable primaryKey)
		throws NoSuchModelException, SystemException {
		return findByPrimaryKey(((Long)primaryKey).longValue());
	}

	/**
	 * Finds the private message with the primary key or throws a {@link org.ossr.portlets.pm.NoSuchPrivateMessageException} if it could not be found.
	 *
	 * @param messageId the primary key of the private message to find
	 * @return the private message
	 * @throws org.ossr.portlets.pm.NoSuchPrivateMessageException if a private message with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public PrivateMessage findByPrimaryKey(long messageId)
		throws NoSuchPrivateMessageException, SystemException {
		PrivateMessage privateMessage = fetchByPrimaryKey(messageId);

		if (privateMessage == null) {
			if (_log.isWarnEnabled()) {
				_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + messageId);
			}

			throw new NoSuchPrivateMessageException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
				messageId);
		}

		return privateMessage;
	}

	/**
	 * Finds the private message with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param primaryKey the primary key of the private message to find
	 * @return the private message, or <code>null</code> if a private message with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public PrivateMessage fetchByPrimaryKey(Serializable primaryKey)
		throws SystemException {
		return fetchByPrimaryKey(((Long)primaryKey).longValue());
	}

	/**
	 * Finds the private message with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param messageId the primary key of the private message to find
	 * @return the private message, or <code>null</code> if a private message with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public PrivateMessage fetchByPrimaryKey(long messageId)
		throws SystemException {
		PrivateMessage privateMessage = (PrivateMessage)EntityCacheUtil.getResult(PrivateMessageModelImpl.ENTITY_CACHE_ENABLED,
				PrivateMessageImpl.class, messageId, this);

		if (privateMessage == null) {
			Session session = null;

			try {
				session = openSession();

				privateMessage = (PrivateMessage)session.get(PrivateMessageImpl.class,
						new Long(messageId));
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (privateMessage != null) {
					cacheResult(privateMessage);
				}

				closeSession(session);
			}
		}

		return privateMessage;
	}

	/**
	 * Finds all the private messages.
	 *
	 * @return the private messages
	 * @throws SystemException if a system exception occurred
	 */
	public List<PrivateMessage> findAll() throws SystemException {
		return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Finds a range of all the private messages.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param start the lower bound of the range of private messages to return
	 * @param end the upper bound of the range of private messages to return (not inclusive)
	 * @return the range of private messages
	 * @throws SystemException if a system exception occurred
	 */
	public List<PrivateMessage> findAll(int start, int end)
		throws SystemException {
		return findAll(start, end, null);
	}

	/**
	 * Finds an ordered range of all the private messages.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param start the lower bound of the range of private messages to return
	 * @param end the upper bound of the range of private messages to return (not inclusive)
	 * @param orderByComparator the comparator to order the results by
	 * @return the ordered range of private messages
	 * @throws SystemException if a system exception occurred
	 */
	public List<PrivateMessage> findAll(int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		Object[] finderArgs = new Object[] {
				String.valueOf(start), String.valueOf(end),
				String.valueOf(orderByComparator)
			};

		List<PrivateMessage> list = (List<PrivateMessage>)FinderCacheUtil.getResult(FINDER_PATH_FIND_ALL,
				finderArgs, this);

		if (list == null) {
			StringBundler query = null;
			String sql = null;

			if (orderByComparator != null) {
				query = new StringBundler(2 +
						(orderByComparator.getOrderByFields().length * 3));

				query.append(_SQL_SELECT_PRIVATEMESSAGE);

				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);

				sql = query.toString();
			}
			else {
				sql = _SQL_SELECT_PRIVATEMESSAGE.concat(PrivateMessageModelImpl.ORDER_BY_JPQL);
			}

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				if (orderByComparator == null) {
					list = (List<PrivateMessage>)QueryUtil.list(q,
							getDialect(), start, end, false);

					Collections.sort(list);
				}
				else {
					list = (List<PrivateMessage>)QueryUtil.list(q,
							getDialect(), start, end);
				}
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FIND_ALL,
						finderArgs);
				}
				else {
					cacheResult(list);

					FinderCacheUtil.putResult(FINDER_PATH_FIND_ALL, finderArgs,
						list);
				}

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Removes all the private messages from the database.
	 *
	 * @throws SystemException if a system exception occurred
	 */
	public void removeAll() throws SystemException {
		for (PrivateMessage privateMessage : findAll()) {
			remove(privateMessage);
		}
	}

	/**
	 * Counts all the private messages.
	 *
	 * @return the number of private messages
	 * @throws SystemException if a system exception occurred
	 */
	public int countAll() throws SystemException {
		Object[] finderArgs = new Object[0];

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
				finderArgs, this);

		if (count == null) {
			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(_SQL_COUNT_PRIVATEMESSAGE);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, finderArgs,
					count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Initializes the private message persistence.
	 */
	public void afterPropertiesSet() {
		String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
					com.liferay.util.service.ServiceProps.get(
						"value.object.listener.org.ossr.portlets.pm.model.PrivateMessage")));

		if (listenerClassNames.length > 0) {
			try {
				List<ModelListener<PrivateMessage>> listenersList = new ArrayList<ModelListener<PrivateMessage>>();

				for (String listenerClassName : listenerClassNames) {
					listenersList.add((ModelListener<PrivateMessage>)InstanceFactory.newInstance(
							listenerClassName));
				}

				listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
			}
			catch (Exception e) {
				_log.error(e);
			}
		}
	}

	public void destroy() {
		EntityCacheUtil.removeCache(PrivateMessageImpl.class.getName());
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST);
	}

	@BeanReference(type = PrivateMessagePersistence.class)
	protected PrivateMessagePersistence privateMessagePersistence;
	@BeanReference(type = ResourcePersistence.class)
	protected ResourcePersistence resourcePersistence;
	@BeanReference(type = UserPersistence.class)
	protected UserPersistence userPersistence;
	private static final String _SQL_SELECT_PRIVATEMESSAGE = "SELECT privateMessage FROM PrivateMessage privateMessage";
	private static final String _SQL_COUNT_PRIVATEMESSAGE = "SELECT COUNT(privateMessage) FROM PrivateMessage privateMessage";
	private static final String _ORDER_BY_ENTITY_ALIAS = "privateMessage.";
	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No PrivateMessage exists with the primary key ";
	private static Log _log = LogFactoryUtil.getLog(PrivateMessagePersistenceImpl.class);
}